import { auth } from 'utils/auth.js';
import { get, post} from 'utils/request.js';
import { config } from 'config.js';

let configs = config();
var app = getApp();
Page({
    data: {
      tags: [
      ],
      pits: {
      },
      waitings: {
      },
      roateAnimationData: {},
      downAnimationData: {},
      isOpen: false,
      map:{
        zoom: 14,
        markers: [],
        polyline: [],
        steps: []
      },
      currentLatitude: null,
      currentLongitude: null,
      id: null,
      womenPits: [],
      menPits: [],
      iconPathMap: {
        'green':  require('../../images/com/green.png'),
        'greenSelected':  require('../../images/com/green-selected.png'),

        'yellow':  require('../../images/com/yellow.png'),
        'yellowSelected':  require('../../images/com/yellow-selected.png'),

        'red':  require('../../images/com/red.png'),
        'redSelected':  require('../../images/com/red-selected.png')
      },
      iconError: require('../../images/com/error.svg'),
      onLine: true,
      noAuth: false,
      hasMobile: 0,
      isMore: 0,
      isAvailable: 1
    },
    onLoad: function(options) {

      this.setData({
        id: options.id
      })

      var roateAnimation = wx.createAnimation({
      transformOrigin: "50% 50%",
       timingFunction: "ease"
      })
      var downAnimationData = wx.createAnimation({
       transformOrigin: "50% 50%",
       timingFunction: "ease"
      })
      this.roateAnimation = roateAnimation;
      this.downAnimationData = downAnimationData;
    },
    onReady(){
      this.mapCtx = wx.createMapContext('Map');
    },
    onShow(){
      var that = this;
      var wiimobile = wx.getStorageSync('wiimobile');
      var hasMobile = wiimobile ? 1 : 0 ;

      that.setData({
        hasMobile: hasMobile
      })
      that.loadToilets();
    },
    onRefreshTap(e){
      var that = this;
      that.setData({
        onLine: true
      });
      that.loadToilets();
    },
    onAbnorTap(e){
      wx.openSetting({
        success:function(res){
          if (!res.authSetting["scope.userInfo"] || !res.authSetting["scope.userLocation"]) {
            
          }
        }
      })
    },
    loadToilets(){
      var that = this;
      
      wx.getLocation({
        type: 'gcj02',
        success: function(res) {
          var latitude = res.latitude;
          var longitude = res.longitude;

          that.data.currentLatitude =  latitude;
          that.data.currentLongitude = longitude;


          console.log(that.data.currentLongitude);
          console.log(that.data.currentLongitude);
          console.log('++++++++++++++++++++++++++++++++++++');

          that.getData({lat: that.data.currentLatitude, lng: that.data.currentLongitude, id: that.data.id}, that);
        },
        fail: function(res){

          //关闭loading
          wx.hideLoading();
          //没有权限
          that.setData({
            noAuth: true
          });
        }
      })

    },
    getData(obj, context){
      wx.showLoading({
        title: '加载中'
      });
      get({'path': configs.toiletDetail}, obj).then(function(res){
          if(res.data.ret == 0){
            var data = res.data.data;

            var points = [];
            data.routes.polyline.map(function(el, index){

              var point = {
                latitude: el.lat,
                longitude: el.lng
              }
              points.push(point)
            })

            var polyline = [{
              color:"#ffc74b",
              points: points,
              width: 6
            }]

            var icon_type = data.icon_type || 1;
            var tempIconPath;
            if(icon_type == 1){
              tempIconPath = context.data.iconPathMap.greenSelected;
            }else if(icon_type == 2){
              tempIconPath = context.data.iconPathMap.yellowSelected;
            }else if(icon_type == 3){
              tempIconPath = context.data.iconPathMap.redSelected;
            }

            var markers = [{
              latitude: data.routes.to.lat,
              longitude: data.routes.to.lng,
              width: 47,
              height: 53,
              iconPath: tempIconPath
            }];

            
            var menPits = data.real_status.men_pits;
            var womenPits = data.real_status.women_pits;   
            var isMore = 0;
            if(data.tags.length > 4){
              isMore = 1;
            }
            

            context.setData({
              'map.polyline': polyline,
              'map.markers': markers,
              'map.zoom': data.zoom,
              id: data.id,
              name: data.name,
              image_url: data.image_url,
              isAi: data.is_ai,
              tags: data.tags,
              isMore: isMore,
              pits: data.pits,
              waitings: data.waitings,
              menPits: menPits,
              womenPits: womenPits,
              currentLatitude: context.data.currentLatitude,
              currentLongitude:  context.data.currentLongitude,
              noAuth: false,
              onLine: true
            })
            context.mapCtx.moveToLocation();
            // // //关闭loading
            wx.hideLoading();
          }else if(res.data.ret == 1 && res.data.errorcode == '4000'){
            context.setData({
              isAvailable: 0
            })
            wx.hideLoading();
            
            wx.showModal({
              title: ' ',
              content: '很抱歉，该厕所暂时不能使用已为您推荐周边其他厕所',
              showCancel: false,
              confirmColor: '#1abed5',
              success: function(res) {
                if (res.confirm) {
                  wx.redirectTo({
                    url: '/pages/index/index'
                  })
                }
              }
            })
          }
      }, function(res){
        //关闭loading
        wx.hideLoading();
        //有可能是参数有问题或者是网络
        context.setData({
          onLine: false,
          noAuth: false
        });
      })
    },
    pickUpTap(){
      var menPitsLength = this.data.menPits.length;
      var womenPitsLength = this.data.womenPits.length;

      var length = Math.max(menPitsLength, womenPitsLength);
      var height = null;
      if(length >= 0 && length <= 4){
        height = 180;
      }else if(length >4 &&  length <= 8){
        height = 230;
      }else if( length > 8 && length <= 12){
        height = 326;
      }else if( length > 12 && length <= 16){
        height = 402;
      }

      if(!this.data.isOpen){
        this.roateAnimation.rotate(-180).step();
        this.downAnimationData.height(height).step();
        this.setData({
          roateAnimationData: this.roateAnimation.export(),
          downAnimationData: this.downAnimationData.export(),
          isOpen: true,
          pitsShow: '40'
        })
         
      }else{
        this.roateAnimation.rotate(0).step();
        this.downAnimationData.height(0).step();
        this.setData({
          roateAnimationData: this.roateAnimation.export(),
          downAnimationData: this.downAnimationData.export(),
          isOpen: false,
          pitsShow: '352'
        })
         
      }
      
    },
    goNavigateTap(e){
      var dataset = e.currentTarget.dataset;
      var latitude = dataset.latitude;
      var longitude = dataset.longitude;
      var id = dataset.id;


      wx.navigateTo({
        url: `/pages/navigate/navigate?latitude=${latitude}&longitude=${longitude}&id=${id}`
      })
    },
    getPhoneNumber: function(e) { 
      // console.log(e.detail.errMsg) 
      // console.log(e.detail.iv) 
      // console.log(e.detail.encryptedData);
      var mobile = e.detail.encryptedData;
      var iv = e.detail.iv;
      var that = this;
      var id = e.target.dataset.id;
      var name = e.target.dataset.name;
      
      var wiimobile = wx.getStorageSync('wiimobile');

      if(mobile == 'getPhoneNumber:fail user deny'){

      }else {
        console.log(wiimobile+'-------------------------->')
          if(wiimobile){
            wx.navigateTo({
              url: `/pages/complaint/complaint?id=${id}&name=${name}`
            })
          }else{
            post({'path': configs.mobileBind}, {encrypted_data: mobile, iv: iv}).then(function(res){
                console.log('-------------------+++++++');
                console.log(typeof res);
                // // //根据返回的结果marker在地图上面
                if(res.data.ret == 0){
                  var outTempData = res.data;
                  var mobile = outTempData.data.mobile;
                  wx.setStorageSync('wiimobile', mobile);

                  wx.navigateTo({
                    url: `/pages/complaint/complaint?id=${id}&name=${name}`
                  })
                }else{
                  wx.showToast({
                    title: '请求失败',
                    image: that.data.iconError
                  })
                }
                
                
            }, function(res){
              wx.showToast({
                title: '请求失败',
                image: that.data.iconError
              })
            })
          }
      }
      
    },
    goComplaintTap(e){
      var id = e.target.dataset.id;
      var name = e.target.dataset.name;
      wx.navigateTo({
        url: `/pages/complaint/complaint?id=${id}&name=${name}`
      })
    }
})
